/*
 * ServerT.cpp
 *
 *  Created on: May 27, 2011
 *      Author: stud
 */
#include <iostream>
#include <string.h>
#include "Thread.h"
#include "ServerSocket.h"
#include "SocketException.h"

#include "DataDef.h"

#include <stdio.h>

#include "ServerThread.h"

ServerT::ServerT(ThreadPriority pri, string _name, ServerSocket *ss,MemoryMaps * localData) :
	Thread(pri, _name) {
	_mmapRef = localData;
	new_sock = ss;
}

void copyData(unsigned char * dest, char * source)
{
	int i = 20;

	printf("From copy function");

	for(i=0;i<20;i++)
	{
		dest[i] = atoi(&source[i]);
		printf(" %d ",dest[i]);
	}

	printf("end copy function");
}

void ServerT::run ()
{
	int cnt,aux;
	char buf[100];

	unsigned char received[50];
	sWord copy[50];

	try {
		while (true) {
			std::string data;

			cnt = new_sock->recv2(received);

			int shift=1;
			int count = 0;
			for(aux=0;aux<20;aux++)
			{
				copy[aux].Bytes.ByteHi = received[count];
				copy[aux].Bytes.ByteLo = received[count+shift];
				count = count +2;
			}


			printf("\n Data from socket");
			for(aux=0;aux<20;aux++)
				{
					printf("\nByte Hi: %d Byte Lo: %d",copy[aux].Bytes.ByteHi, copy[aux].Bytes.ByteLo);

				}
			printf("\n END Data from socket");

			_mmapRef->setMapContents(0,copy);
			_mmapRef->writeFlagUp();

			sleep(1000);

			/*
			for(aux = 0;aux<20;aux++)
			{

			}*/

			/*
			cnt = new_sock->recv(data);

			strncpy(buf, data.c_str(), cnt);
			std::cout << "Got:" << cnt << " " << buf << "\n";

			int iter = 0;
			for(iter = 0;iter<20;iter++)
			{
				printf("data at pos %d: %d\n",iter, int(data[iter]));
			}


			printf("\n!!!Received data: ");
			iter = 0;
			printf("In unsigned format !!!: ");

			printf("_ In unsigned format!!! END");
			_localData->setData((sWord *)received);
		/*	if(buf[0]==0)
				_localData->initMap(2);*/
			//new_sock->send(data);*/
		}
	} catch (SocketException&) {
	}

}

ServerT::~ServerT() {
	delete(new_sock);
}

